package com.telnikoff.ts.core;

import java.io.File;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.telnikoff.log.Log;

public class Workspace 
{
	private static final String NAME = "Workspace";
	
	private static final class ProjectHolder
	{
		static List<Project> projects;
		
		static List<Project> getProjects(Workspace workspace)
		{
			if (null == projects)
			{
				projects = new CopyOnWriteArrayList<Project>();
				File[] fs = workspace.dir.listFiles();
				for (File f : fs)
					projects.add(new Project(workspace, f));
			}
			return projects;
		}
	}
	
	private final File dir;
	
	public Workspace(String workspaceDir)
	{
		Log.info(NAME, "using dir '"+workspaceDir+"'.");
		
		dir = new File(workspaceDir);
		if (!dir.exists())
		{
			Log.info(NAME, "Workspace dir does not exist, creating...");
			
			if (!dir.mkdirs())
				Log.warn(NAME, "Failed to create workspace dir '"+workspaceDir+"'.");
			
			else
				Log.info(NAME, "Workspace dir created.");
		}
	}
	
	public Project createProject(String name)
	{
		return new Project(this, name);
	}
	
	void save(Project p)
	{
		Log.debug(NAME, "Saving "+p);
	}
	
	public List<Project> getProjects()
	{
		return ProjectHolder.getProjects(this);
	}
}
